<?php


namespace app\socket\controller;


use app\api\services\GatewayService;
use app\common\model\DebugModel;
use app\common\services\RedisService;
use app\socket\services\LoginService;
use app\socket\services\ConnectService;
use app\socket\services\LogService;
use app\socket\services\MessageService;
use think\worker\Server;
use Workerman\Lib\Timer;

class Events2 extends Server
{
    protected static $ReDB;
    protected $socket = 'http://0.0.0.0:9092';
    protected $name = 'ImService';
    /**
     * 当客户端连接时触发
     * @param $client_id
     */
    public static function onConnect($client_id){
//        echo 'new user: '.$client_id . "\n";
//        DebugModel::addInfo(0,'connect');

        LogService::clear();//先清理历史的日志文件111

        //连接成果发送消息
        LogService::save('客户端连接',['client_id'=>$client_id]);
    }

    /**
     * 客户端发来消息时 触发
     * @param $client_id
     * @param $message
     *      type  pong 心跳返回
     */
    public static function onMessage($client_id,$message){
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";

        LogService::save('客户端消息',"client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message);


        $message_data = json_decode($message,true);
        if(!$message_data)return ;

        switch ($message_data['type']){
            //心跳返回
            case 'pong': return;
            //登录
            case 'login':
                LoginService::Login3($message_data,$client_id);
                break;
                // 消息已读
            case 'read':
                MessageService::upRedaMsg($message_data,$client_id);
                break;
        }
    }



    /**
     * 守护进程时 启动 常驻内存
     * @param $businessWorker\
     */
    public static function onWorkerStart($businessWorker){
//        echo "1111111\n\n";
        // 调用Redis模型
//        $redis = RedisService::getInstance();
        if (RedisService::$status !== true) {
//            Exception('redis服务出错' . RedisService::$status);
        }
//        self::$ReDB = $redis;

        //只有id编号为0的进程上设置定时器 其他1,2,3,号进程不设置定时器
        if($businessWorker->id ===0){
            //定时器1  20 秒执行一次任务
//            Timer::add(30,function(){
//                echo date('Y-m-d H:i:s')."\n";
//            });
        }

    }

    /**
     * 当客户端断开连接时
     * @param $client_id
     */
    public static function onClose($client_id){

        //debug
        echo "close==> client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n\n";

        //向大厅 发送离线消息
        GatewayService::onlineStateClient($client_id,0);

    }

}